package com.michale.common.result;

import com.michale.common.character.ClassConvert;
import com.michale.common.constants.PageConstant;
import com.michale.common.utils.Ip.ServletUtils;
import com.michale.common.utils.String.StringUtils;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

import static com.michale.common.constants.PageConstant.*;

/**
 * @author Michale
 * @apiNote 分页参数
 */
public class PageParam implements Serializable {

    @ApiModelProperty("当前记录起始索引")
    private Integer pageNum;
    @ApiModelProperty("每页显示记录数")
    private Integer pageSize;
    @ApiModelProperty("排序字段")
    private String orderByColumn;
    @ApiModelProperty("排序的方式desc或者asc")
    private String Asc = PageConstant.ASC;
    @ApiModelProperty("分页参数合理化")
    private Boolean reasonable = true;

    /**
     * 封装分页对象
     */
    public static PageParam getPageParam() {
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(ClassConvert.toInt(ServletUtils.getParameter(PAGE_NUM), 1));
        pageParam.setPageSize(ClassConvert.toInt(ServletUtils.getParameter(PAGE_SIZE), 5));
        pageParam.setOrderByColumn(ServletUtils.getParameter(ORDER_FIELD));
        pageParam.setIsAsc(ServletUtils.getParameter(IS_ASC));
        pageParam.setReasonable(ServletUtils.getParameterToBool(String.valueOf(REASONABLE)));
        return pageParam;
    }

    public static PageParam buildPageRequest() {
        return getPageParam();
    }

    public String getOrderBy() {
        if (StringUtils.isEmpty(orderByColumn)) {
            return "";
        }
        return StringUtils.toUnderScoreCase(orderByColumn) + " " + Asc;
    }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public String getOrderByColumn() {
        return orderByColumn;
    }

    public void setOrderByColumn(String orderByColumn) {
        this.orderByColumn = orderByColumn;
    }

    public String getIsAsc() {
        return Asc;
    }

    public void setIsAsc(String isAsc) {
        if (StringUtils.isNotEmpty(isAsc)) {
            // 兼容前端排序类型
            if (ASCENDING.equals(isAsc)) {
                isAsc = PageConstant.ASC;
            } else if (PageConstant.DESCENDING.equals(isAsc)) {
                isAsc = PageConstant.DESC;
            }
            this.Asc = isAsc;
        }
    }

    public Boolean getReasonable() {
        if (StringUtils.isNull(reasonable)) {
            return Boolean.TRUE;
        }
        return reasonable;
    }

    public void setReasonable(Boolean reasonable) {
        this.reasonable = reasonable;
    }
}
